import { Dictionary } from "../../Common/Dictionary";
import { IDictionary } from "../../Interfaces/IUtils";
import { IDataFactory, IDataContainer } from "../../Interfaces/IDataTable";
import ADQ from "../../Core/ADQ";
import DataContainer from "./DataContainer";
import CloneTools from "../../Utils/CloneTools";

/**
 * 数据工厂
 * TIPS:id重复则数据将被替换
 */
export class DataFactory implements IDataFactory {
  remove(tag: number, id: number): boolean {
    return this.dataList.get(tag).remove(id);
  }
  addArrayToSort(tag: number, data: any[]) {
    if (data == null) {
      console.warn("数据工厂：添加数组排序错误，数据不能为控！");
      return;
    }
    data.sort((left, right) => {
      return left[ADQ.IdName] - right[ADQ.IdName];
    });
    this.addArray(tag, data);
  }
  constructor() {
    this.dataList = new Dictionary<number, DataContainer>();
  }
  private dataList: IDictionary<number, DataContainer>;
  /**
   * 添加单条数据
   * @param tag 数据标识、指明数据属于什么类型，如角色、特效等，建议使用枚举控制
   * @param data 表数据
   */
  add(tag: number, data: any) {
    if (!this.dataList.containsKey(tag)) {
      var container = new DataContainer(tag.toString());
      this.dataList.set(tag, container);
    }
    this.dataList.get(tag).set(data);
  }
  /**批量添加数据 */
  addArray(tag: number, data: Array<any>) {
    if (!this.dataList.containsKey(tag)) {
      var container = new DataContainer(tag.toString());
      this.dataList.set(tag, container);
    }
    var container = this.dataList.get(tag);
    data.forEach((data) => {
      container.set(data);
    });
  }
  /**获取数据通过数据编号 */
  getDataByID<T>(tag: number, id: number): T {
    if (this.dataList.containsKey(tag)) {
      var getValue = this.dataList.get(tag).get(id);
      if (getValue == null) return null;
      else return Object.assign({}, getValue) as T;
    } else {
      console.error("数据不存在：标识" + tag + ",ID" + id);
      return null;
    }
  }

  getDataList<T>(tag: number): Array<T> {
    if (this.dataList.containsKey(tag)) {
      return CloneTools.deepCopy(this.dataList.get(tag).dataList.values) as T[];
    } else {
      console.error("数据不存在：标识" + tag);
      return null;
    }
  }
}
